package com.soft.base.mybatis;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.soft.base.protocol.PaginateResult;
import com.soft.base.protocol.PaginateResult;

import java.util.ArrayList;
import java.util.List;
/**
 * class
 *
 * @author user
 * @date 2020/06/05
 */
public class PaginateUtil {
    public static <T> PaginateResult<T> convert(IPage<T> page) {
        PaginateResult<T> result = new PaginateResult<T>();
        result.setPage(page.getCurrent());
        result.setPageSize(page.getSize());
        result.setTotal(page.getTotal());
        result.setRecords(page.getRecords());
        return result;
    }

    public static <T> PaginateResult<T> pack(List<T> records, long page, long pageSize) {
        PaginateResult<T> result = new PaginateResult<T>();
        result.setPage(page);
        result.setPageSize(pageSize);
        result.setTotal(records.size());
        int start = (int) (pageSize * (page - 1));
        if (start < 0 || start >= records.size()) {
            result.setRecords(new ArrayList<>());
        } else {
            result.setRecords(records.subList(start, Math.min((int) (start + pageSize), records.size())));
        }
        return result;
    }

    public static <TO> PaginateResult<TO> pack(List<TO> records) {
        PaginateResult<TO> paginate = new PaginateResult<>();
        paginate.setTotal(records.size());
        paginate.setPage(1);
        paginate.setPageSize(records.size());
        if (paginate.getPageSize() == 0L) {
            paginate.setPageSize(1);
        }
        paginate.setRecords(records);
        return paginate;
    }
}
